using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.ConnectionEngine.Common;

namespace Microsoft.ConnectionEngine.Common
{
    /// <summary>
    /// This is the adapter exception handler
    /// </summary>
    [ConfigurationElementType(typeof(CustomHandlerData))]
    class SystemAdapterExceptionHandler : IExceptionHandler
    {
        private static int id;
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="ignore"></param>
        public SystemAdapterExceptionHandler(NameValueCollection ignore)
        {
            id = -1;
        }

        /// <summary>
        /// This is the method from the IExceptionHandler interface
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="correlationID"></param>
        /// <returns></returns>
        public Exception HandleException(Exception exception, Guid correlationID)
        {
            //Perform logging
            LogEntry logEntry = new LogEntry();
            logEntry.EventId = ++id;
            logEntry.Priority = GetPriority(exception);
            logEntry.Message = GetMessage(exception);
            logEntry.Categories.Add("General");
            Logger.Write(logEntry);
            return exception;
        }

        private string GetMessage(Exception ex)
        {
            StringBuilder sb = new StringBuilder();
            if (ex.GetType() == typeof(SystemAdapterException))
            {
                SystemAdapterException sysEx = (SystemAdapterException)ex;
                sb.Append(SystemAdapterException.GetExceptionDescription(sysEx.Cause));
            }
            sb.Append("\r\n" + ex.Message);
            return sb.ToString();
        }

        private int GetPriority(Exception ex)
        {
            //Changed by sajoshi
            // WorkItem 157 : Used variable ret to return value.
            int ret = 0;
            if (ex.GetType() == typeof(SystemAdapterException))
            {
                SystemAdapterException sysEx = (SystemAdapterException)ex;
                ret = SystemAdapterException.GetPriority(sysEx.Cause );
            }
            else
            {
               ret=1;
            }
            return ret;
        }
    }
}
